package kr.or.kead.ui.insert_update;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import kr.or.kead.service.DaoTable;

public abstract class AbsInsertUpdate extends JDialog implements ActionListener {
	private JPanel btnp;
	private JPanel mainp;
	private JButton btnOk;
	private JButton btnNo;
	protected Object obj;
	private String title;
	protected DaoTable daotable;
	private int res;
	
	public AbsInsertUpdate(Object obj, String title) {
		
		this.obj = obj;
		this.title = title;
		initialize();
		pack();
		setModal(true);
	}
	private void initialize() {
		initDao();
		setLayout(new BorderLayout(0, 0));
		
		btnp = new JPanel();
		add(btnp, BorderLayout.SOUTH);
		
		btnOk = new JButton("추가");
		btnOk.addActionListener(this);
		btnp.add(btnOk);
		
		btnNo = new JButton("취소");
		btnNo.addActionListener(this);
		btnp.add(btnNo);
		
		mainp = getMainPanel();
		add(mainp, BorderLayout.CENTER);
		if(obj!=null){//수정
			setTitle(title+"수정");
			btnOk.setText("수정");
			updateInit();
		}
		else{
			setTitle(title+"추가");
		}
	}

	
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnNo) {
			dispose();
		}
		if (e.getSource() == btnOk) {
			btnOkActionPerformed(e);
		}
	}
	protected void btnOkActionPerformed(ActionEvent e) {
		if(isValidCheck()){
			Object obj = getObject();
			if(e.getActionCommand()=="추가"){
				isOk(daotable.insertDao(obj),"삽입");
			}else{
				isOk(daotable.updateDao(obj),"수정");
			}
			dispose();
		}
	}
	
	private void isOk(int result, String msg) {
		this.res = result;
		if(result == 0){
			JOptionPane.showMessageDialog(null, msg+"완료");
		}else{
			JOptionPane.showMessageDialog(null, msg+"실패");
		}
	}
	public int showDialog(){
		return res;
	}
	
	protected abstract void initDao();
	protected abstract boolean isValidCheck();
	protected abstract JPanel getMainPanel();
	protected abstract Object getObject() ;
	protected abstract void updateInit();
}
